<template>
  <div  class="api">
     <div class="search-term">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
        <el-form-item label="路径">
          <el-input placeholder="路径" v-model="searchInfo.path" clearable></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input placeholder="描述" v-model="searchInfo.description" clearable></el-input>
        </el-form-item>
        <el-form-item label="api组">
          <el-input placeholder="api组" v-model="searchInfo.apiGroup" clearable></el-input>
        </el-form-item>
        <el-form-item label="请求">
          <el-select clearable placeholder="请选择" v-model="searchInfo.method" >
            <el-option
              :key="item.value"
              :label="`${item.label}(${item.value})`"
              :value="item.value"
              v-for="item in methodOptions"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery" icon="el-icon-search"  type="primary">查询</el-button>
        </el-form-item>
      </el-form>
      <el-form>
        <el-form-item>
          <el-button @click="openDialog('create')" type="primary">新增api</el-button>
        </el-form-item>
      </el-form>
     </div>
    <el-table :data="tableData" @sort-change="sortChange" border stripe>
      <el-table-column label="id" min-width="60" prop="ID" sortable="custom"></el-table-column>
      <el-table-column label="api路径" min-width="150" prop="path" sortable="custom"></el-table-column>
      <el-table-column label="api分组" min-width="150" prop="apiGroup" sortable="custom"></el-table-column>
      <el-table-column label="api简介" min-width="150" prop="description" sortable="custom"></el-table-column>
      <el-table-column label="请求" min-width="150" prop="method" sortable="custom">
        <template slot-scope="scope">
          <div>
            {{scope.row.method}}
            <el-tag
              :key="scope.row.methodFileters"
              :type="scope.row.method|tagTypeFileters"
              effect="dark"
              size="mini"
            >{{scope.row.method|methodFileters}}</el-tag>
            <!-- {{scope.row.method|methodFiletr}} -->
          </div>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button @click="updateApi(scope.row)" size="small" type="primary" icon="el-icon-edit">编辑</el-button>
          <el-button @click="deleteApi(scope.row)" size="small" type="danger" icon="el-icon-delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="page"
      :page-size="pageSize"
      :page-sizes="[10, 30, 50, 100]"
      :style="{float:'right',padding:'20px'}"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
    <!-- 新增api弹窗 -->
    <el-dialog  :title="dialogTitle" :visible.sync="dialogFormVisible" width="600px" >
      <el-form  :model="form" :rules="rules" label-width="110px" ref="apiForm">
        <el-form-item label="路径" prop="path" >
          <el-input autocomplete="on" v-model.trim ="form.path" style="width: 90%"></el-input>
        </el-form-item>
        <el-form-item label="请求" prop="method">
              <el-select placeholder="请选择" v-model="form.method" style="width: 220px">
                <el-option
                        :key="item.value"
                        :label="`${item.label}(${item.value})`"
                        :value="item.value"
                        v-for="item in methodOptions"
                ></el-option>
              </el-select>
            </el-form-item>
        <el-form-item label="api分组" prop="apiGroup">
          <el-input autocomplete="on" v-model="form.apiGroup" style="width: 90%"></el-input>
        </el-form-item>
        <el-form-item label="api简介" prop="description">
          <el-input autocomplete="on" v-model="form.description" style="width: 90%"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button @click="enterDialog" type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
// 获取列表内容封装在mixins内部  getTableData方法 初始化已封装完成 条件搜索时候 请把条件安好后台定制的结构体字段 放到 this.searchInfo 中即可实现条件搜索

import {
  getApiById,
  getApiList,
  createApi,
  updateApi,
  deleteApi
} from '@/api/api'
import infoList from '@/mixins/infoList'
import { toSQLLine } from '@/utils/stringFun'
const methodOptions = [
  {
    value: 'POST',
    label: '创建',
    type: 'success'
  },
  {
    value: 'GET',
    label: '查看',
    type: ''
  },
  {
    value: 'PUT',
    label: '更新',
    type: 'warning'
  },
  {
    value: 'DELETE',
    label: '删除',
    type: 'danger'
  }
]

export default {
  name: 'Api',
  mixins: [infoList],
  data() {
    return {
      listApi: getApiList,
      dialogFormVisible: false,
      dialogTitle: '新增Api',
      dialogType: "add",
      form: {
        path: '',
        apiGroup: '',
        method: '',
        description: ''
      },
      searchInfo: {
        path: undefined,
        description: undefined,
        apiGroup: undefined,
        method: undefined
      },
      methodOptions: methodOptions,
      type: '',
      rules: {
        path: [{ required: true, message: '请输入api路径', trigger: 'blur' }],
        apiGroup: [
          { required: true, message: '请输入组名称', trigger: 'blur' }
        ],
        method: [
          { required: true, message: '请选择请求方式', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入api介绍', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 排序
    sortChange({ prop, order }) {
      if (prop) {
        this.searchInfo.orderKey = toSQLLine(prop)
        this.searchInfo.desc = order == 'descending'
      }
      this.getTableData()
    },
    //条件搜索前端看此方法
    handleQuery(){
      this.getTableData()
    },
    initForm() {
      this.$refs.apiForm.resetFields()
      this.form= {
        path: '',
        apiGroup: '',
        method: '',
        description: ''
      }
    },
    closeDialog() {
      this.initForm();
      this.dialogFormVisible = false
    },
    openDialog(type) {
      switch (type) {
        case 'create':
          this.dialogTitle = '新增Api';
          break
        case 'update':
          this.dialogTitle = '编辑Api'
          break
        default:
          break
      }
      this.type = type
      this.dialogFormVisible = true
    },
    async updateApi(row) {
      const res = await getApiById({ id: row.ID })
      this.form = res.data.api
      this.openDialog('update')
    },
    async deleteApi(row) {
      this.$confirm('此操作将永久删除所有角色下该菜单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await deleteApi(row)
          if (res.code == 0) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getTableData()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async enterDialog() {
      this.$refs.apiForm.validate(async valid => {
        if (valid) {
          switch (this.type) {
            case 'create':
              {
                const res = await createApi(this.form)
                if (res.code == 0) {
                  this.$message({
                    type: 'success',
                    message: '添加成功',
                    showClose: true
                  })
                }
               await this.getTableData()
                this.closeDialog()
              }

              break
            case 'update':
              {
                const res = await updateApi(this.form)
                if (res.code == 0) {
                  this.$message({
                    type: 'success',
                    message: '编辑成功',
                    showClose: true
                  })
                }
               await this.getTableData()
                this.closeDialog()
              }
              break
            default:
              {
                this.$message({
                  type: 'error',
                  message: '未知操作',
                  showClose: true
                })
              }
              break
          }
        }
      })
    }
  },
  filters: {
    methodFileters(value) {
      const target = methodOptions.filter(item => item.value === value)[0]
      // return target && `${target.label}(${target.value})`
      return target && `${target.label}`
    },
    tagTypeFileters(value) {
      const target = methodOptions.filter(item => item.value === value)[0]
      return target && `${target.type}`
    }
  },
  created(){
    this.getTableData()
  }
}
</script>
<style scoped lang="scss">
  .api {
    .el-input-number {
      margin-left: 15px;
      span {
        display: none;
      }
    }
    .button-box {
      padding: 10px 20px;
      .el-button {
        float: right;
      }
    }
  }
  .role-box {
    .el-tabs__content {
      height: calc(100vh - 150px);
      overflow: auto;
    }
  }
</style>
